package com.sh.sh_ai_agent.tools;

import cn.hutool.core.io.FileUtil;
import com.sh.sh_ai_agent.constont.FileConstant;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.File;

public class FileOperationTool {

    private final String FILE_DIR = FileConstant.FILE_SAVE_DIR + "/file";

    @Tool(description = "Read content from a file")
    public String readFile(@ToolParam(description = "Name of the file to read") String fileName) {
        try {
            File file = FileUtil.file(FILE_DIR, fileName);
            if (!file.isFile()) {
                return "Error reading file: Not a file: " + file.getAbsolutePath();
            }
            return FileUtil.readUtf8String(file);
        } catch (Exception e) {
            return "Error reading file: " + e.getMessage();
        }
    }


    @Tool(description = "Write content to a file")
    public String writeFile(
            @ToolParam(description = "Name of the file to write") String fileName,
            @ToolParam(description = "Content to write to the file") String content) {
        try {
            // 构造完整文件路径
            File file = FileUtil.file(FILE_DIR, fileName);
            // 创建上级目录（不是文件本身）
            FileUtil.mkdir(file.getParentFile());
            // 写入内容
            FileUtil.writeUtf8String(content, file);
            return "File written successfully to: " + file.getAbsolutePath();
        } catch (Exception e) {
            return "Error writing to file: " + e.getMessage();
        }
    }

}
